package com.moco.launcher.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;

import com.moco.launcher.LauncherApplication;
import com.moco.launcher.R;
import com.moco.launcher.fragment.ADRFragment;
import com.moco.launcher.fragment.BaseFragment;
import com.moco.launcher.fragment.PauseFragment;
import com.moco.launcher.listener.FragmentListener;
import com.oazon.common.Assert;
import com.oazon.common.Logger;

public class PopActivity extends BaseFragmentActivity implements FragmentListener ,OnClickListener{
	private static final String TAG = "PopActivity";
	
	private LauncherApplication mApp = null;
	private BaseFragment fragment = null;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.setContentView(R.layout.pop_layout);
		
		mApp = ((LauncherApplication) getApplication());
		mApp.registerActivty(this);
		
		Intent intent = this.getIntent();
		String type = intent.getStringExtra("fragment_type");
		Assert.notNEWS(type);
		Logger.d(TAG, "type=" + type);
		if (type.equals("adr")) {
			fragment = new ADRFragment();
		} else if (type.equals("pause")) {
			fragment = new PauseFragment((Bitmap)mApp.getTempObject(type));
		} else if (type.equals("finish")) {
			fragment = new PauseFragment(null);
			finishActivity();
		}
		
		Assert.notNull(fragment);
		fragment.registerCallback(this);
		getSupportFragmentManager().beginTransaction().replace(R.id.fragment, fragment).commit();
	}

	@Override
	public synchronized void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
		setIntent(intent);
		
		String type = intent.getStringExtra("fragment_type");
		Logger.d(TAG, "onNewIntent    type=" + type);
		if(type == null)
			return;

		if (type.equals("adr")) {
			Logger.d(TAG, "adr onNewInternt");
		} else if (type.equals("pause")) {
			fragment = new PauseFragment((Bitmap)mApp.getTempObject(type));
			getSupportFragmentManager().beginTransaction().replace(R.id.fragment, fragment).commit();
		} else if (type.equals("finish")) {
			finishActivity();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Logger.d(TAG, "the launcher onKeyDown event");
		final boolean handled = super.onKeyDown(keyCode, event);

		// Eat the long press event so the keyboard doesn't come up.
		if (keyCode == KeyEvent.KEYCODE_MENU && event.isLongPress())
			return true;

		return handled;
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {
		Logger.d(TAG, "the launcher receive dispatchTouchEvent event");
		mApp.resetStartTime();
		return super.dispatchTouchEvent(event);
	}

	@Override
	public void finishActivity() {
		this.finish();
		overridePendingTransition(R.anim.pop_in, R.anim.pop_out);
	}

	@Override
	public void onClick(View v) {
		finishActivity();
	}
}
